# 模拟请求

import requests
import json
import time
import os
import sys
from urllib.parse import urljoin
import webbrowser

# 服务基础URL
PORT = 5020
BASE_URL = f"http://127.0.0.1:{PORT}"

def start_stimulus_extraction(task_info, video_path, threshold):
    
    # 获取任务信息
    print(f"任务创建成功，ID: {task_info['task_id']}")
    
    # 步骤2: 打开UI页面让用户选择点
    ui_url = urljoin(BASE_URL, task_info['ui_addr'])
    # ui_url = task_info['ui_addr']
    print(f"请在打开的浏览器窗口中选择LED点位置...")
    webbrowser.open(ui_url)
    
    # 步骤3: 等待处理完成
    progress_url = urljoin(BASE_URL, task_info['progress_pipe_addr'])
    result_url = urljoin(BASE_URL, task_info['result_addr'])
    # progress_url = task_info['progress_pipe_addr']
    # result_url = task_info['result_addr']
    
    print("等待处理完成...")
    while True:
        try:
            progress_response = requests.get(progress_url)
            progress_data = progress_response.json()
            
            # 如果出错
            if "error" in progress_data and progress_data["error"]:
                print(f"处理出错: {progress_data['error']}")
                return
                
            # 打印进度
            if progress_data["status"] == "Running":
                sys.stdout.write(f"\r进度: {progress_data['percentage']}%")
                sys.stdout.flush()
            
            # 如果完成
            if progress_data["status"] == "Completed":
                print("\n处理完成!")
                break
                
            time.sleep(1)
        except Exception as e:
            print(f"\n获取进度失败: {e}")
            time.sleep(2)
    
    # 步骤4: 获取结果
    try:
        result_response = requests.get(result_url)
        result_data = result_response.json()
        
        # 打印结果摘要
        stimulus_frames = result_data.get("stimulus_frames", [])
        print(f"共找到 {len(stimulus_frames)} 个刺激帧")
        
        if stimulus_frames:
            print(f"前10个刺激帧: {stimulus_frames[:10]}")
            
        # 保存结果到文件
        result_file = "stimulus_result.json"
        with open(result_file, "w") as f:
            json.dump(result_data, f, indent=2)
        print(f"完整结果已保存到: {result_file}")
        
    except Exception as e:
        print(f"获取结果失败: {e}")

def start_stimulus_param_user_input(task_info):
    # 获取任务信息
    task_id = task_info['task_id']
    print(f"任务创建成功，ID: {task_id}")
    
    # 步骤2: 打开UI页面让用户输入参数
    ui_url = urljoin(BASE_URL, task_info['ui_addr'])
    print(f"请在打开的浏览器窗口中输入刺激参数...")
    webbrowser.open(ui_url)
    
    # 步骤3: 等待用户输入完成
    result_url = urljoin(BASE_URL, task_info['result_addr'])
    
    print("等待用户输入参数...")
    print("按Ctrl+C可以取消等待")
    
    # 创建一个标志，用于判断用户是否已提交参数
    params_submitted = False
    
    try:
        while not params_submitted:
            # 尝试通过轮询检查结果是否可用
            try:
                # 调用GET请求获取结果
                result_response = requests.get(result_url)
                
                # 如果请求成功且状态码为200，说明参数已提交
                if result_response.status_code == 200:
                    result_data = result_response.json()
                    params_submitted = True
                    print("\n参数提交成功!")
                    break
            except requests.exceptions.RequestException as e:
                # 处理请求异常
                if hasattr(e, 'response') and e.response is not None:
                    if e.response.status_code == 404:
                        # 404错误通常表示参数尚未提交
                        print(".", end="", flush=True)
                    else:
                        print(f"\n获取结果出错 (HTTP {e.response.status_code}): {str(e)}")
                else:
                    print(f"\n请求失败: {str(e)}")
                
            # 等待一段时间后再次检查
            time.sleep(2)
    except KeyboardInterrupt:
        print("\n用户取消等待")
        return
    
    # 步骤4: 获取并显示结果
    try:
        # 显示提交的参数
        print("用户提交的刺激参数:")
        print(f"- 刺激位置: {result_data.get('position', '未提供')}")
        print(f"- 刺激频率: {result_data.get('frequency', '未提供')} Hz")
        
        if 'voltage' in result_data and result_data['voltage'] is not None:
            print(f"- 刺激电压: {result_data['voltage']} V")
        
        if 'current' in result_data and result_data['current'] is not None:
            print(f"- 刺激电流: {result_data['current']} mA")
        
        # 保存结果到文件
        result_file = "stimulus_params_result.json"
        with open(result_file, "w", encoding='utf-8') as f:
            json.dump(result_data, f, ensure_ascii=False, indent=2)
        print(f"参数已保存到: {result_file}")
        
        return result_data
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        print(f"获取参数失败: {e}")
        return None
